<template>
  <div>
    <!-- 渲染角色列表 -->
    <!-- 多选框组 -->
    <el-checkbox-group v-model="roleIds">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="setRloeFn">确定</el-button>
        <el-button size="small" @click="cancleDialog">取消</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getRolesAPI } from '@/api/setting'

import { getUserDetailById } from '@/api/user'

import { setAssignRoleAPI } from '@/api/employees'
export default {
  name: 'AssignRole',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      roleIds: [], // 用户已分配的角色列表
      roleList: [] // 全部角色列表
    }
  },
  created() {
    this.getRolesListFn()
    this.getUserDetailByFn()
  },
  methods: {
    // 给用户分配角色
    async setRloeFn() {
      const res = await setAssignRoleAPI({ id: this.roleId, roleIds: this.roleIds })
      console.log(res)
      this.$message.success(res.message)
      this.$emit('closeDialog')
    },
    // 获取用户的基本信息
    async  getUserDetailByFn() {
      const res = await getUserDetailById(this.roleId)
      // 如果后端返回的数据，不是空数组，而是null，需要让后端进行调整
      this.roleIds = res.data.roleIds === null ? [] : res.data.roleIds
    },
    // 获取角色列表
    async getRolesListFn() {
      const res = await getRolesAPI()
      this.roleList = res.data.rows
    },
    // 点击取消按钮
    cancleDialog() {
      this.$emit('closeDialog')
    }
  }
}
</script>

<style>
.el-checkbox-group{
  margin-bottom: 20px;
}
</style>
